package com.qingke.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.qingke.dao.ProductManagementDAO;
import com.qingke.pojo.Product;

@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProductManagementDAO dao=new ProductManagementDAO();
       
    public UpdateServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		String fileDir = getServletContext().getRealPath("/img");
		System.out.println(fileDir);
		String fileName="";
		String date="";
		String type="";
		int size=0;	 
		String address="";
		Integer id=null;
		String name="";
		String description="";
		Double price=null;
		Integer quantity=null;
		Product product=null;
		if(ServletFileUpload.isMultipartContent(request)){		 
			DiskFileItemFactory factory=new DiskFileItemFactory();
			factory.setSizeThreshold(20*1024);
			ServletFileUpload upload=new ServletFileUpload(factory);
			upload.setHeaderEncoding("utf-8");
			int MaxSize=10*1024*1024;
			List<FileItem> formlists=null;			 
			try {
				//这里居然要完整的上传完成，才能继续下面的代码，用户体验太差
				formlists=upload.parseRequest(request);
				
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			Iterator<FileItem> iter=formlists.iterator(); 
			while(iter.hasNext()){		 
				FileItem formItem=iter.next();	
				
				if(!formItem.isFormField()){
					//获取图片名
					fileName=formItem.getName();
					//类型
					type=formItem.getContentType();
					//大小
					size=(int) formItem.getSize();
					//时间
					System.out.println(fileName);
					System.out.println(date);
					System.out.println(type);
					System.out.println(size);
					if(fileName==null||fileName.equals("")&&formItem.getSize()==0){
						//文件为空，上传失败！
					}
					else{
						if(size>MaxSize){
							//文件大于10MB，上传失败！
							response.getWriter().println("<script>alert('文件大于10MB，上传失败！')</script>");
							break;
						}
						//地址
						address="upload/" + fileName;
						System.out.println(address);
						File saveFile=new File(fileDir+"\\"+fileName);
						try {
							formItem.write(saveFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
						product.setImage(fileName);
					}
				}
				else{
					String key=formItem.getFieldName();
					String value=formItem.getString("utf-8");
					switch(key){
					case "id":
						id=Integer.valueOf(value);
						product=dao.selectById(id);
						break;
					case "name":
						name=value;
						break;
					case "description":
						description=value;
						break;
					case "price":
						price=Double.valueOf(value);
						break;
					case "quantity":
						quantity=Integer.valueOf(value);
						break;
					}
					System.out.println(key+":"+value);
				}
			}
			
			product.setName(name);
			product.setDescription(description);
			product.setPrice(price);
			product.setQuantity(quantity);
			boolean isSuccess=dao.updateProduct(product);
			if(isSuccess){
				response.getWriter().println("<script>alert('修改成功');window.location.href='list.html';</script>");
			}
			else{
				response.getWriter().println("<script>alert('修改失败');window.history.back();</script>");
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
